package jack.app.stepdefinitions;

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.options.BaseOptions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import jack.app.activepages.HomePage;
import net.serenitybdd.annotations.Steps;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;

/**
 * @ClassName HomePageStepdefs
 * @Date 2024/11/12 14:43 59
 * @Author Jack Chen
 * @Description serenity-cucumber-app-ui-test-project
 * @Version 1.0
 */

public class HomePageStepdefs {
    private AndroidDriver driver;
    private WebDriverWait wait;

    @Steps
    HomePage homePage;

    @When("user click the aliyunpan app")
    public void userClickTheAliyunpanApp() {
        By by = By.xpath("//android.widget.ImageView[@content-desc=\"阿里云盘\"]");
        if (isElementFound(by)) {
            driver.findElement(by).click();
        } else {
            //Todo
            //"com.alicloud.databox/.MainActivity"
        }
    }

    private boolean isElementFound(By locator) {
        WebElement element = driver.findElement(locator);
        return element.isDisplayed();
    }

    @Then("^aliyunpan app is opened successfully$")
    public void aliyunpanAppIsOpenedSuccessfully() {
        WebElement in = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//android.widget.LinearLayout[@resource-id=\"com.alicloud.databox:id/layoutContent\"]/android.widget.RelativeLayout/android.widget.RelativeLayout")));

        in.click();
    }

    @Given("user click databox element")
    public void userClickDataboxElement() {
        homePage.clickDataBoxContent();
    }

    @Given("mobile session established")
    public void mobileSessionEstablished() {
        var options = new BaseOptions()
                .amend("appium:deviceName", "RedMiNote 11T pro")
                .amend("appium:automationName", "UiAutomator2")
                .amend("platformName", "Android")
                .amend("appium:ensureWebviewsHavePages", true)
                .amend("appium:nativeWebScreenshot", true)
                .amend("appium:newCommandTimeout", 3600)
                .amend("appium:connectHardwareKeyboard", true);
        try{
            URL url = new URL("http://127.0.0.1:4723");
            driver = new AndroidDriver(url, options);
            wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}
